//
//  lyfDataBaseHandle.m
//  UI 豆瓣完整版
//
//  Created by dllo on 16/1/12.
//  Copyright © 2016年 lanou. All rights reserved.
//

#import "lyfDataBaseHandle.h"
#import "MovieModel.h"
#import "FMDB.h"
#define kDocumentPath [NSSearchPathForDirectoriesInDomains(NSDocumentDirectory, NSUserDomainMask, YES) lastObject]
#define DBPATH(name) document stringByAppendingPathComponent:name

@interface lyfDataBaseHandle ()
@property (nonatomic, retain) FMDatabase *dbPoint;

@end

@implementation lyfDataBaseHandle

+ (lyfDataBaseHandle *)sharedDataBaseHandle {
    // 创建静态指针
    static lyfDataBaseHandle *handle = nil;
    // 创建对象
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        // 执行一次
        handle = [[lyfDataBaseHandle alloc] init];
    });
    return handle;
}

- (void)openDB {
    // 路径
    NSString *document = kDocumentPath;
    // 拼接
    NSString *dbPath = [DBPATH(@"豆瓣.sqlite")];
    // 创建数据库
    self.dbPoint = [FMDatabase databaseWithPath:dbPath];
    BOOL result = [_dbPoint open];
    if (result) {
        NSLog(@"打开数据库成功");
    } else {
        NSLog(@"打开数据库失败");
    }
    NSLog(@"%@", document);
    
}



- (void)createTable {
    // sql语句
    NSString *sqlStr = [NSString stringWithFormat:@"create table if not exists Movie(number integer primary key autoincrement, title text)"];
    [self executeSQLString:sqlStr showInfo:@"建表"];
}

- (void)insertModel:(MovieModel *)model {
    NSString *sqlStr = [NSString stringWithFormat:@"insert into Movie(title) values('%@')", model.title];
    [self executeSQLString:sqlStr showInfo:@"增"];
}

- (void)deleteModel:(MovieModel *)model {
    NSString *sqlStr = [NSString stringWithFormat:@"delete from Movie where title = '%@'", model.title];
    [self executeSQLString:sqlStr showInfo:@"删"];
}

- (void)updateModel:(MovieModel *)model {
    NSString *sqlStr = [NSString stringWithFormat:@"update Movie set title = '%@'", model.title];
    [self executeSQLString:sqlStr showInfo:@"改"];
}

- (NSMutableArray *)selectTable {
    NSString *sqlStr = [NSString stringWithFormat:@"select * from Movie"];
    NSMutableArray *arrModel = [NSMutableArray array];
    FMResultSet *set = [_dbPoint executeQuery:sqlStr];
    while ([set next]) {
        NSString *title = [set stringForColumn:@"title"];
        [arrModel addObject:title];
    }
    
    return arrModel;
    
}

- (void)executeSQLString:(NSString *)sqlStr showInfo:(NSString *)info {
    BOOL result = [_dbPoint executeUpdate:sqlStr];
    NSString *str = @"";
    if (result) {
        str = [NSString stringWithFormat:@"%@ success", info];
    } else {
        str = [NSString stringWithFormat:@"%@ failed", info];
    }
    NSLog(@"%@", str);
}



@end
